package org.dromara.business.modules.demands.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.business.modules.demands.domain.BuDemands;
import org.dromara.business.modules.demands.domain.bo.BuDemandsBo;
import org.dromara.business.modules.demands.domain.vo.BuDemandsVo;
import org.dromara.business.modules.demands.mapper.BuDemandsMapper;
import org.dromara.business.modules.demands.service.IBuDemandsService;
import org.dromara.business.modules.message.service.IBuMessageService;
import org.dromara.common.core.constant.RoleConstants;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.system.domain.bo.AuditBo;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * 需求信息Service业务层处理
 *
 * @author ckk
 * @date 2025-10-20
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class BuDemandsServiceImpl implements IBuDemandsService {

    private final IBuMessageService buMessageService;
    private final BuDemandsMapper baseMapper;

    /**
     * 查询需求信息
     *
     * @param id 主键
     * @return 需求信息
     */
    @Override
    public BuDemandsVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询需求信息列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 需求信息分页列表
     */
    @Override
    public TableDataInfo<BuDemandsVo> queryPageList(BuDemandsBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<BuDemands> lqw = buildQueryWrapper(bo);
        Page<BuDemandsVo> result = baseMapper.queryPageList(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的需求信息列表
     *
     * @param bo 查询条件
     * @return 需求信息列表
     */
    @Override
    public List<BuDemandsVo> queryList(BuDemandsBo bo) {
        LambdaQueryWrapper<BuDemands> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<BuDemands> buildQueryWrapper(BuDemandsBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<BuDemands> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(BuDemands::getId);
        lqw.eq(StringUtils.isNotBlank(bo.getTitle()), BuDemands::getTitle, bo.getTitle());
        lqw.eq(bo.getCategoryId() != null, BuDemands::getCategoryId, bo.getCategoryId());
        lqw.eq(bo.getBudgetNegotiable() != null, BuDemands::getBudgetNegotiable, bo.getBudgetNegotiable());
        lqw.like(StringUtils.isNotBlank(bo.getLocation()), BuDemands::getLocation, bo.getLocation());
        lqw.eq(StringUtils.isNotBlank(bo.getUrgency()), BuDemands::getUrgency, bo.getUrgency());
        lqw.like(StringUtils.isNotBlank(bo.getContactName()), BuDemands::getContactName, bo.getContactName());
        lqw.like(StringUtils.isNotBlank(bo.getContactPhone()), BuDemands::getContactPhone, bo.getContactPhone());
        lqw.eq(bo.getStatus() != null, BuDemands::getStatus, bo.getStatus());
        return lqw;
    }

    /**
     * 新增需求信息
     *
     * @param bo 需求信息
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(BuDemandsBo bo) {
        BuDemands add = MapstructUtils.convert(bo, BuDemands.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改需求信息
     *
     * @param bo 需求信息
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(BuDemandsBo bo) {
        BuDemands update = MapstructUtils.convert(bo, BuDemands.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(BuDemands entity) {
        boolean anyMatch = LoginHelper.getLoginUser().getRoles().stream().anyMatch(role -> role.getRoleId().equals(RoleConstants.MERCHANT));
        if (anyMatch) {
            entity.setStatus(1);
        }
    }

    /**
     * 校验并批量删除需求信息信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    @Override
    public Boolean audit(AuditBo bo) {
        return new LambdaUpdateChainWrapper<>(baseMapper)
            .in(BuDemands::getId, Arrays.asList(bo.getIds().split(",")))
            .set(BuDemands::getStatus, bo.getStatus())
            .set(bo.getStatus() == 2, BuDemands::getReason, bo.getReason())
            .update();
    }

    @Override
    public TableDataInfo<BuDemandsVo> frontList(BuDemandsBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<BuDemands> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getCategoryId() != null, BuDemands::getCategoryId, bo.getCategoryId());
        lqw.in(BuDemands::getStatus, 0, 3);
        lqw.like(StringUtils.isNotBlank(bo.getTitle()), BuDemands::getTitle, bo.getTitle());
        Page<BuDemandsVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    @Override
    public BuDemandsVo getInfo(Long id) {
        BuDemandsVo vo = baseMapper.selectVoById(id);
        new LambdaUpdateChainWrapper<>(baseMapper)
            .eq(BuDemands::getId, id)
            .set(BuDemands::getViewCount, vo.getViewCount() + 1)
            .update();
        return vo;
    }
}
